package bd403.UIComponents;

import java.util.InputMismatchException;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.Toast;
import bd403.Backend.Drink;
import bd403.Backend.DrinkParams;
import bd403.Backend.DrinkStorage;
import bd403.namespace.BDActivity;
import bd403.namespace.R;
import bd403.utils.KeyboardSetup;

/* UI and functionality for the Add page of the BrewDawg application.
 * Main authors: Cody & Brenden
 */

public class AddActiv extends Activity {
	
	private static final int DEFAULT_RATING = 3;
	private static final double DEFAULT_INTERVAL = 1.0;
	
	/* Initializes the the UI for the page.
	 */
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initialize();
    }
	
	/* Initializes the Add page UI onCreate and onResume.
	 */
	private void initialize() {
		setContentView(R.layout.add);
        
        // Initialize the rating bar
        final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
        ratingbar.setRating(DEFAULT_RATING);
        
        // Force rating bar to only accept full stars (beers)
        ratingbar.setStepSize((float)DEFAULT_INTERVAL);
        setupKeyboard();
        setupSubmitListener();
        setAutoComplete();
	}
	
	/* Sets up the soft keyboard to minimize on a 'Return' key click.
	 */
	private void setupKeyboard() {
		final EditText nameText = (EditText) findViewById(R.id.beerName);
        final EditText commentText = (EditText) findViewById(R.id.commentText);
        
        KeyboardSetup ks = KeyboardSetup.getInstance(this);
        
        ks.setupKeyboard(nameText);
		ks.setupKeyboard(commentText);
	}
	
	/* Initialize a listener for the '+ Add Drink' button.
	 */
	private void setupSubmitListener() {
		final EditText nameText = (EditText) findViewById(R.id.beerName);
	    final EditText commentText = (EditText) findViewById(R.id.commentText);
	    final RadioGroup typeGroup = (RadioGroup) findViewById(R.id.radioGroupType);
	    final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
		
	    // Set up the listener for a drink submission
	    Button next = (Button) findViewById(R.id.submit);
	    next.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View view) {
	            Intent intent = new Intent();
	            setResult(RESULT_OK, intent);
	            
	            // Pull the drink information from the form
	            String drinkName = nameText.getText().toString().trim();
	            String comment = commentText.getText().toString().trim();
	            RadioButton checkedRadioButton = (RadioButton) findViewById(typeGroup.getCheckedRadioButtonId());
	            String type = (String) checkedRadioButton.getTag();
	            int rating = (int) ratingbar.getRating();
	            DrinkStorage ds = BDActivity.getStorage();
	            	
	            DrinkParams dp = null;
	            try {
	            	if (validateInput(drinkName, type, comment)) {
	            		dp = new DrinkParams(drinkName, comment, rating, type);
	            		if (!ds.addDrink(dp)) {
		    				Toast.makeText(getApplicationContext(), getString(R.string.toast_add_noconn), Toast.LENGTH_SHORT).show();
		    			} else {
		    				// Transition to the individual drink page
		    				Toast.makeText(getApplicationContext(), getString(R.string.toast_add_success) + dp.getName(), Toast.LENGTH_SHORT).show();
		    				ds.setCurrentDrink(ds.getDrinkByName(dp.getName()));
		    				startActivity(new Intent(getApplicationContext(), DrinkViewActiv.class));
		    			}
	            	}
	            } catch (InputMismatchException e) {
	            	// Exception from validateInput
	            	Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            	} catch (IllegalStateException e) {
            		// Means this drink already exists in the application
            		Drink current = ds.getDrinkByName(dp.getName());
            		if (current != null) {
            			Toast.makeText(getApplicationContext(), current.getName() + getString(R.string.toast_add_drinkexists), Toast.LENGTH_SHORT).show();
            			// Found a match, send them to the drink page of the drink they tried to add
            			ds.setCurrentDrink(current);
	    				startActivity(new Intent(getApplicationContext(), DrinkViewActiv.class));
            		} else {
            			// Shows the user about an error without a connection
            			Toast.makeText(getApplicationContext(), getString(R.string.toast_add_noconn), Toast.LENGTH_SHORT).show();
            		}
            	}
	        }
	    });
	}
	
	/* Returns true if this drink is valid, otherwise throws an InputMismatchException.
	 */
	private boolean validateInput(String drinkName, String type, String comment) {
		if (drinkName == null || drinkName.equals("")) {
			throw new InputMismatchException(getString(R.string.add_submiterr_blank));
		} else if (!(type.equals("Beer") | type.equals("Wine") | type.equals("Mixed"))) {
			throw new InputMismatchException(getString(R.string.add_submiterr_type));
		} else if (!validChar(drinkName.toLowerCase(), false)) {
			throw new InputMismatchException(getString(R.string.add_submiterr_name));
		} else if (!validChar(comment.toLowerCase(), true)) {
			throw new InputMismatchException(getString(R.string.add_submiterr_comment));
		}
		return true;
	}
	
	/* Returns true if this input String contains all legal characters. Otherwise returns false.
	 * If indicator is false, the input is a Drink name. If indicator is true, input is a comment.
	 * Legal characters for a Drink name include all alphabetic characters, and spaces.
	 * Legal characters for a comment include all alphabetic characters, spaces, exclamation,
	 * and period.
	 */
	private boolean validChar(String input, boolean indicator) {
		// a = 97, z = 122
		if (indicator) {
			for (int i = 0; i < input.length(); i++) {
				if (input.charAt(i) < 'a' || input.charAt(i) > 'z') {
					if (input.charAt(i) != ' ' && input.charAt(i) != '!' && input.charAt(i) != '.') {
						return false;
					}
				}
			}
			return true;
		} else {
			for (int i = 0; i < input.length(); i++) {
				if (input.charAt(i) < 'a' || input.charAt(i) > 'z') {
					if (input.charAt(i) != ' ') {
						return false;
					}
				}
			}
			return true;
		}
	}
	
	/* Sets up auto completion for the Drink name form on the Add page.
	 */
	private void setAutoComplete() {
		AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.beerName);
		DrinkStorage ds = BDActivity.getStorage();
		
		// prevents program from crashing if DrinkStorage isn't found
		// useful for AddActivTest.java
		if (ds == null) {
			return;
		}
		List<String> drinkNames = ds.getDrinkNames();
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, drinkNames);
	    textView.setAdapter(adapter);
	}
	
	/* Refreshes the Add page when a user comes back to it after adding a drink.
	 */
	protected void onResume() {
		super.onResume();
        initialize();
	}
}